<template>
  <div class="goods-modal-content component-goods">
    <div class="goods-form">
      <el-form
        ref="searchFormRef"
        inline
        :model="searchForm"
        label-width="108px"
        @submit.prevent
      >
        <el-form-item :label="$t('shopFeature.goods.prodName') + '：'">
          <el-input
            v-model.trim="searchForm.keyword"
            clearable
            :placeholder="$t('pcdecorate.shopMessage.prodNameTips')"
          />
        </el-form-item>
        <el-form-item :label="$t('pcdecorate.shopMessage.goodsCategory')+'：'">
          <el-cascader
            v-model="selectedCategory"
            expand-trigger="hover"
            :options="categoryList"
            :props="categoryTreeProps"
            :clearable="true"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="searchbtn"
            @click="handleSearch"
          >
            {{ $t('pcdecorate.commonModal.search') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tables">
      <el-table
        ref="multipTableRef"
        v-loading="tableLoading"
        style="width: 100%"
        :header-cell-class-name="isSelectAllShow ? 'table-select-all-header' : 'table-header'"
        row-class-name="table-row-low"
        row-key="prodId"
        :data="tableList"
        height="320"
        :class="{'tables-checkedbox': !isMulilt}"
        @select-all="handleSelectAll"
        @select="handleCancelSelected"
        @selection-change="handleSelectChange"
      >
        <el-table-column
          type="selection"
          :reserve-selection="true"
        />
        <el-table-column
          prop="prodName"
          min-width="150px"
          :label="$t('pcdecorate.shopMessage.goods')"
          align="left"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div
              class="names"
              style="display: flex;align-items: center"
            >
              <el-image
                :src="checkFileUrl(scope.row.pic)"
                style="width: 48px;height: 48px;margin-right: 15px"
              >
                <template #error>
                  <div class="image-slot">
                    <img
                      src="@/assets/img/def.png"
                      alt
                    >
                  </div>
                </template>
              </el-image>
              <span
                style="width: calc(100% - 65px);overflow:hidden;text-overflow: ellipsis;white-space: nowrap"
              >{{ scope.row.prodName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="price"
          width="140px"
          :label="$t('pcdecorate.shopMessage.goodsPrice')"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span style="color: #E1251B ">￥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="totalStocks"
          width="120px"
          :label="$t('pcdecorate.shopMessage.inventory')"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.prodType === 2 ? scope.row.seckillSearchVO?.seckillTotalStocks : scope.row.totalStocks }}
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 12px; text-align: right;"
        :current-page="perProps.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="perProps.perPage"
        layout="->, total, sizes, prev, pager, next, jumper"
        :total="perProps.total"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>
  </div>
</template>
<script setup>
import { treeDataTranslate, checkFileUrl } from '@/utils/index.js'

const props = defineProps({
  activeName: {
    type: String,
    default: () => ''
  },
  currentGoodsType: { // 商品类型
    type: String,
    default: () => 'normal'
  },
  goodsType: { // 商品类型
    type: [String, Number],
    default: () => ''
  },
  isMulilt: { // 是否支持多选
    type: Boolean,
    default: () => false
  },
  goodsNumber: { // 限制添加的个数
    type: [String, Number],
    default: () => 0
  },
  dataUrl: { // 活动的url
    type: String,
    default: ''
  },
  prodType: { // 类型
    type: Number,
    default: null
  },
  deviceType: { // 弹窗类型 pc端： pc , 移动:mobile
    type: String,
    default: () => 'pc'
  },
  echoDataList: { // 回显数据
    type: Array,
    default: () => []
  },
  customLinkArr: { // 自定义链接回显数据
    type: Object,
    default: () => {}
  },
  isSelectAllShow: { // 是否显示全选
    type: Boolean,
    default: () => false
  }
})
const emit = defineEmits([
  'handleGoodsSelect',
  'handleGoodsSelect',
  'handleGoodsSelect',
  'handleGoodsSelect',
  'handleGoodsSelect'
])

const searchForm = reactive({}) //  查询条件
const tableList = ref([]) // 商品列表
const perProps = { // 分页
  perPage: 10,
  page: 1,
  total: 0
}

const categoryList = ref([]) // 商品分类下拉列表
const selectedCategory = ref([]) // 选中的商品分类
const categoryTreeProps = reactive({
  value: 'categoryId',
  label: 'categoryName'
})

let showEchData = [] // 回显数据
let multipleSelection = [] // 表格选中的数据
watch(() => props.activeName, async (val) => {
  if (val === '1') { // 当前是选择商品
    searchForm.keyword = ''
    selectedCategory.value = ''
    searchForm.categoryId = ''
    // 获取商品分类
    await getGoodsCategoryList()
    // 回显数据
    if (isShowData()) { // 判断如果在操作热区
      const obj = {
        name: props.customLinkArr.title || props.customLinkArr.name,
        id: props.customLinkArr.link,
        imgs: '',
        brief: ''
      }
      const arr = []
      arr.push(obj)
      showEchData = JSON.parse(JSON.stringify(arr))
      // 做这一步是为了商品组件等下可以将之前选的数据和用户操作的商品进行合并(保证点击确定的时候字段名一样)
      if (!props.prodType) { // 非移动活动商品
        compoundName()
      }
      multipleSelection = showEchData
    } else {
      showEchData = JSON.parse(JSON.stringify(props.echoDataList))
      if (!props.prodType) { // 非移动活动商品
        compoundName()
      }
      multipleSelection = showEchData
    }
    // 获取商品列表
    getGoodsListMessage()
  }
})

const multipTableRef = ref(null)
// 这里拿到取消选中的哪项
const handleCancelSelected = (rows, row) => {
  const selected = rows.length && rows.indexOf(row) != -1
  if (props.isMulilt) { // 如果当前是多选
    // 如果当前是取消勾选的情况
    if (!selected) {
      showEchData.forEach((item, index) => {
        if (item.prodId == row.prodId) {
          showEchData.splice(index, 1)
        }
      })
      multipleSelection.forEach((item, index) => {
        if (item.prodId == row.prodId) {
          multipleSelection.splice(index, 1)
        }
      })
    } else {
      multipleSelection = removeDuplicCateObj([...multipleSelection, row])
      if (props.goodsNumber != 0) { // 如果不为0的情况下，说明用户限制了当前选择的数量
        if (multipleSelection.length > props.goodsNumber) {
          const delRow = multipleSelection.shift()
          tableList.value.forEach(item => {
            if (delRow.prodId == item.prodId) {
              multipTableRef.value?.toggleRowSelection(item, false)
            }
          })
        }
      }
    }
    emit('handleGoodsSelect', { type: 'goodsItem', value: multipleSelection })
  } else { // 单选
    if (!selected) { // 取消选中
      multipleSelection = []
      setTimeout(() => {
        multipleSelection.push(row)
        multipTableRef.value?.toggleRowSelection(row, true)
      }, 100)
    }
  }
}

let flag = false
const handleSelectChange = (rows) => {
  if (flag) return
  multipleSelection = rows
  if (props.isMulilt) { // 当前支持多选
    emit('handleGoodsSelect', { type: 'goodsItem', value: multipleSelection })
  } else { // 否则就是单选
    if (multipleSelection.length > 1) {
      const delRow = multipleSelection.shift()
      tableList.value.forEach(item => {
        if (delRow.prodId == item.prodId) {
          multipTableRef.value?.toggleRowSelection(item, false)
        }
      })
    }
    emit('handleGoodsSelect', {
      type: 'goodsItem',
      value: multipleSelection[0]
    })
  }
}

// 移除重复
const removeDuplicCateObj = (arr) => {
  const obj = {}
  arr = arr.reduce((newArr, next) => {
    if (!obj[next.prodId]) {
      obj[next.prodId] = true
      newArr.push(next)
    }
    return newArr
  }, [])
  return arr
}

const tableLoading = ref(false) // 表格的loading
// 获取商品信息
const getGoodsListMessage = (val) => {
  if (val === 'search') {
    perProps.page = 1
  }
  const { page, perPage } = perProps
  if (props.dataUrl) { // 活动url存在
    tableLoading.value = true
    http({
      url: http.adornUrl(props.dataUrl),
      method: 'get',
      params: http.adornParams({
        current: page,
        size: perPage,
        shopCategoryId: searchForm.categoryId, // 商品分类
        prodType: props.prodType, // 商品类型
        keyword: searchForm.keyword, // 商品名称
        status: 1,
        isActive: 1 // 过滤活动商品
      })
    }).then(({ data }) => {
      tableList.value = data.records
      perProps.total = data.total
      tableLoading.value = false
      setDataShow(val)
    }).catch(() => {
      tableLoading.value = false
    })
  } else { // 普通商品
    tableLoading.value = true
    http({
      url: http.adornUrl('/admin/search/prod/renovationPage'),
      method: 'get',
      params: http.adornParams({
        prodType: searchForm.prodType, // 商品类型
        shopCategoryId: searchForm.categoryId, // 商品分类
        keyword: searchForm.keyword, // 商品名称
        current: page,
        size: perPage,
        status: 1
      })
    }).then(({ data }) => {
      tableList.value = data.records
      perProps.total = data.total
      tableLoading.value = false
      setDataShow(val)
    }).catch(() => {
      tableLoading.value = false
    })
  }
}
// 分页每页多少条
const onPageSizeChange = (val) => {
  perProps.perPage = val
  showEchData = multipleSelection
  getGoodsListMessage()
}
// 分页当前第几页
const onPageChange = (val) => {
  perProps.page = val
  showEchData = multipleSelection
  getGoodsListMessage()
}
// 搜索
const handleSearch = () => {
  getGoodsListMessage('search')
}
// 选择商品分类
const handleChange = (val) => {
  searchForm.categoryId = val[val.length - 1]
}
// 获取商品分类
const getGoodsCategoryList = () => {
  return new Promise((resolve) => {
    http({
      url: http.adornUrl('/prod/category/listCategory'),
      method: 'get',
      params: http.adornParams({
        maxGrade: 2,
        status: 1
      })
    }).then(({ data }) => {
      categoryList.value = treeDataTranslate(data, 'categoryId', 'parentId')
      searchForm.prodType = props.goodsType
      resolve(true)
    }).catch(() => {

    })
  })
}

// 数据回显
const setDataShow = (val) => {
  flag = true
  nextTick(() => {
    if (val === 'search') {
      multipTableRef.value && multipTableRef.value?.clearSelection() // 清除上一次回显内容
    }
    const prodIds = multipleSelection.map(x => x.prodId)
    tableList.value.forEach(item => {
      if (prodIds.indexOf(item.prodId) > -1) {
        multipTableRef.value?.toggleRowSelection(item, true)
      }
    })
    // 回显的时候，需要emit通知父组件这次是回显，可以直接点击确定
    if (isShowData() || !props.isMulilt) { // 单选通知
      emit('handleGoodsSelect', { type: 'goodsItem', value: multipleSelection[0] })
    } else { // 多选通知
      emit('handleGoodsSelect', { type: 'goodsItem', value: multipleSelection })
    }
    setTimeout(() => {
      flag = false
    }, 200)
  })
}

// 判断当前是否是多选回显还是单选回显
const isShowData = () => {
  return props.customLinkArr && props.customLinkArr.type != '' && props.customLinkArr.type === '1'
}

const compoundName = () => {
  showEchData.forEach(item => {
    item.prodName = item.name || item.prodName // 商品名称
    item.pic = item.imgs || item.pic // 商品图片
    item.brief = item.description || item.brief // 商品描述
    item.oriPrice = item.orignPrice ? item.orignPrice : '' // 商品原价
    if (props.goodsType == 2) {
      item.activityId = item.id // 活动id
    } else {
      item.prodId = item.id || item.prodId // 商品id
    }
  })
}

/**
 * 当用户手动勾选全选 Checkbox 时触发
 * @param {*} rows 勾选项数组
 */
const handleSelectAll = (rows) => {
  if (rows && rows.length) {
    // 选中
    multipleSelection = removeDuplicCateObj([...multipleSelection, ...rows])
  } else {
    // 清空选择
    multipTableRef.value?.clearSelection()
    multipleSelection = []
  }
  emit('handleGoodsSelect', { type: 'goodsItem', value: multipleSelection })
}
</script>

<style lang="scss" scoped>
@use "index";
</style>
